﻿using Microsoft.AspNetCore.Mvc;
using System.Text;
using System;

using Microsoft.AspNetCore.Mvc.Filters;

using Util;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
/// <summary>
/// 鉴权
/// </summary>
namespace Web.Filters
{
    public class MyAuthorizationFilter : IAuthorizationFilter
    {  
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //判断是否开启必须登录
            bool needLogin = false;
            bool.TryParse(ConfigHelper.GetSection("NeedLogin"), out needLogin);
            //判断是否为不需要登录页面
            bool notController = false;
            string controller = context.RouteData.Values["Controller"].ToString();
            //string action = context.RouteData.Values["Action"].ToString();
            List<string> execList = new List<string> { "login", "introduce" };
            if (execList.Contains(controller.ToLower()))//不为登录页面 和 相关介绍页面
            {
                notController = true;
            }
            if (needLogin)
            {
                if (!notController )
                {
                    if (CheckLogin(context))
                    {
                        //权限验证
                        //如果登录的用户名为admin2929，则拥有所有的权限
                        //HttpRequest request = context.HttpContext.Request;
                        CheckAuth();
                    }
                    else
                    {
                        if (false)//如果是网站访问,则返回登录页
                        {
/*                            context.Result = new EmptyResult(); //防止执行后续的代码
                            context.HttpContext.Response.Redirect("/Login/Index");*/
                        }
                        else //返回错误 401
                        {
                            context.Result = new UnauthorizedResult(); 
                        }
                    }
                }
            } 
        } 

        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private bool CheckLogin(AuthorizationFilterContext context)
        {
            #region  session 检查  是否登录超时,默认为30分钟，在startup里设置  
            context.HttpContext.Session.TryGetValue(Utility.AccessToken.AccessTokenName, out Byte[] sessionBytes);
            if (sessionBytes != null)
            {
                string sessionValue = System.Text.Encoding.Default.GetString(sessionBytes);
                context.HttpContext.Request.Cookies.TryGetValue(Utility.AccessToken.AccessTokenName, out string CookieValue);

                if (!sessionValue.Equals(CookieValue))//如果为空，或者session和cookie不一致,则跳转到登录页
                {
                    return false; 
                }
                else
                {
                    //每次操作都重新写入session,30分钟无操作需重新登录
                    context.HttpContext.Session.Set(Utility.AccessToken.AccessTokenName, sessionBytes);
                }
            }
            else
            {
                return false; 
            }
            #endregion

            return true;
        }

        /// <summary>
        /// 权限验证
        /// </summary>
        /// <returns></returns>
        private bool CheckAuth()
        {
            return true;
        }
    }
}
